<template>
  <div class="guard-point-content">
    <el-card>
      <div class="search-bar">
        <el-input v-model="searchName" placeholder="护导点名称" style="width: 200px; margin-right: 10px;" />
        <el-button type="primary" @click="fetchData">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" style="float: right;" @click="openAddDialog">+ 添加护导点</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%; margin-top: 10px;">
        <el-table-column prop="pointName" label="护导点名称" />
        <el-table-column
          prop="createTime"
          label="创建时间"
        >
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="schoolName" label="学校名称" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="edit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        style="margin-top: 20px; text-align: right;"
        @current-change="fetchData"
      />
    </el-card>
    <el-dialog v-model="showAddDialog" :title="editForm.id ? '编辑护导点' : '添加护导点'">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="学校名称">
          <el-input v-model="editForm.schoolName" placeholder="XX市XX区XX学校" />
        </el-form-item>
        <el-form-item label="护导点名称">
          <el-input v-model="editForm.pointName" placeholder="护导点名称" />
        </el-form-item>
        <el-form-item label="偏移范围（米）">
          <el-input v-model="editForm.offsetRange" placeholder="偏移范围" />
        </el-form-item>
        <el-form-item label="地图位置">
          <el-input v-model="editForm.location" placeholder="地图位置" readonly @click="showMap = true" />
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="editForm.longitude" placeholder="经度" readonly />
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="editForm.latitude" placeholder="纬度" readonly />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" type="textarea" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showMap" title="选择地图位置" width="600px" :modal-append-to-body="true">
      <div class="map-search-bar">
        <el-input v-model="schoolSearchName" placeholder="请输入学校全称或具体校区名称" style="width: 300px;" />
        <el-button type="primary" @click="searchSchoolOnMap">搜索</el-button>
        <el-button type="success" circle @click="locateMyPosition" :title="'定位到我的位置'">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="7" stroke="#409EFF" stroke-width="2"/>
            <circle cx="12" cy="12" r="2" fill="#409EFF"/>
            <line x1="12" y1="2" x2="12" y2="5" stroke="#409EFF" stroke-width="2"/>
            <line x1="12" y1="19" x2="12" y2="22" stroke="#409EFF" stroke-width="2"/>
            <line x1="2" y1="12" x2="5" y2="12" stroke="#409EFF" stroke-width="2"/>
            <line x1="19" y1="12" x2="22" y2="12" stroke="#409EFF" stroke-width="2"/>
          </svg>
        </el-button>
      </div>
      <div id="tmap-container" style="height:400px;width:100%"></div>
      <template #footer>
        <el-button @click="showMap = false">取消</el-button>
        <el-button type="primary" @click="confirmMapSelect">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { fetchGuardPointList, addGuardPoint, updateGuardPoint, deleteGuardPoint } from '@/api/guardPoint'
import { ElMessageBox, ElMessage } from 'element-plus'

const searchName = ref('')
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showAddDialog = ref(false)
const showMap = ref(false)
const schoolSearchName = ref('')
const defaultForm = {
  id: null,
  pointName: '',
  schoolName: '',
  longitude: '',
  latitude: '',
  offsetRange: '',
  location: '',
  remark: ''
}
const editForm = ref({ ...defaultForm })
let tmap = null
let marker = null

function fetchData() {
  fetchGuardPointList({ pageNum: currentPage.value, pageSize: pageSize.value, pointName: searchName.value }).then(res => {
    tableData.value = res?.records || []
    total.value = res?.total || 0
    console.log('tableData', tableData.value)
  })
}
function reset() {
  searchName.value = ''
  fetchData()
}
function openAddDialog() {
  Object.assign(editForm.value, defaultForm)
  showAddDialog.value = true
}
function edit(row) {
  editForm.value = { ...row }
  showAddDialog.value = true
}
function del(row) {
  ElMessageBox.confirm(
    '确定要删除该护导点吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteGuardPoint(row.id).then(() => {
      fetchData()
      ElMessage.success('删除成功')
    })
  }).catch(() => {
    // 用户取消，无需处理
  })
}
function save() {
  if (!editForm.value.pointName) {
    window.$message?.warning?.('请输入护导点名称')
    return
  }
  if (!editForm.value.schoolName) {
    window.$message?.warning?.('请输入学校名称')
    return
  }
  if (!editForm.value.longitude || !editForm.value.latitude) {
    window.$message?.warning?.('请选择地图位置')
    return
  }
  if (!editForm.value.offsetRange) {
    window.$message?.warning?.('请输入偏移范围')
    return
  }

  if (editForm.value.id) {
    updateGuardPoint(editForm.value).then(() => {
      showAddDialog.value = false
      fetchData()
      ElMessage.success('更新成功')
    }).catch(err => {
      window.$message?.error?.(err.message || '更新失败')
    })
  } else {
    addGuardPoint(editForm.value).then(() => {
      showAddDialog.value = false
      fetchData()
      ElMessage.success('添加成功')
    }).catch(err => {
      window.$message?.error?.(err.message || '添加失败')
    })
  }
}
function confirmMapSelect() {
  editForm.value.location = '保定理工学院'
  editForm.value.longitude = 115.464806
  editForm.value.latitude = 38.886565
  editForm.value.schoolName = '保定理工学院'
  showMap.value = false
}
function searchSchoolOnMap() {
  if (!schoolSearchName.value) {
    window.$message?.warning?.('请输入学校名称')
    return
  }
  fetch(`https://apis.map.qq.com/ws/geocoder/v1/?address=${encodeURIComponent(schoolSearchName.value)}&key=UEXBZ-Z2ICJ-S6IFH-XKPBM-WXN5K-PJBX5`)
    .then(res => res.json())
    .then(data => {
      if (data.status === 0 && data.result && data.result.location) {
        const { lat, lng } = data.result.location
        const latlng = new window.TMap.LatLng(lat, lng)
        tmap.setCenter(latlng)
        tmap.setZoom(18)
        if (marker) marker.setMap(null)
        marker = new window.TMap.MultiMarker({
          map: tmap,
          geometries: [{
            id: 'school',
            styleId: 'marker',
            position: latlng,
            properties: { title: schoolSearchName.value }
          }]
        })
        editForm.value.schoolName = schoolSearchName.value
        editForm.value.location = `${lat},${lng}`
        editForm.value.latitude = lat
        editForm.value.longitude = lng
      } else {
        window.$message?.error?.('未找到该学校，请检查名称')
      }
    })
    .catch(err => {
      window.$message?.error?.(err.message || '搜索失败')
    })
}
function locateMyPosition() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords
        const latlng = new window.TMap.LatLng(latitude, longitude)
        tmap.setCenter(latlng)
        tmap.setZoom(18)
        if (marker) marker.setMap(null)
        marker = new window.TMap.MultiMarker({
          map: tmap,
          geometries: [{
            id: 'myPosition',
            styleId: 'marker',
            position: latlng,
            properties: { title: '我的位置' }
          }]
        })
        editForm.value.location = `${latitude},${longitude}`
        editForm.value.latitude = latitude
        editForm.value.longitude = longitude
        window.$message?.success?.('已定位到当前位置')
      },
      (error) => {
        window.$message?.error?.(`定位失败：${error.message}`)
      }
    )
  } else {
    window.$message?.error?.('您的浏览器不支持地理定位')
  }
}
function formatDate(val) {
  if (!val) return '-'
  const date = new Date(val)
  if (isNaN(date.getTime())) return val
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  const h = String(date.getHours()).padStart(2, '0')
  const min = String(date.getMinutes()).padStart(2, '0')
  const s = String(date.getSeconds()).padStart(2, '0')
  return `${y}-${m}-${d} ${h}:${min}:${s}`
}
watch(showMap, async (val) => {
  if (val) {
    await nextTick()
    if (!window.TMap) {
      const script = document.createElement('script')
      script.src = 'https://map.qq.com/api/gljs?v=1.exp&key=UEXBZ-Z2ICJ-S6IFH-XKPBM-WXN5K-PJBX5'
      document.head.appendChild(script)
      script.onload = () => initMapWithMarker()
    } else {
      initMapWithMarker()
    }
  } else {
    if (marker) {
      marker.setMap(null)
      marker = null
    }
  }
})
function initMapWithMarker() {
  // 先清空地图容器，防止地图重复渲染
  const mapContainer = document.getElementById('tmap-container')
  if (mapContainer) mapContainer.innerHTML = ''

  let lat = Number(editForm.value.latitude) || 38.886565
  let lng = Number(editForm.value.longitude) || 115.464806
  tmap = new window.TMap.Map('tmap-container', {
    center: new window.TMap.LatLng(lat, lng),
    zoom: 15
  })
  if (lat && lng) {
    marker = new window.TMap.MultiMarker({
      map: tmap,
      geometries: [{ id: 'point', styleId: 'marker', position: new window.TMap.LatLng(lat, lng) }]
    })
  }
  tmap.on('click', (evt) => {
    const { lat, lng } = evt.latLng
    editForm.value.latitude = lat
    editForm.value.longitude = lng
    editForm.value.location = `${lat},${lng}`
    if (marker) marker.setMap(null)
    marker = new window.TMap.MultiMarker({
      map: tmap,
      geometries: [{ id: 'point', styleId: 'marker', position: new window.TMap.LatLng(lat, lng) }]
    })
  })
}
onMounted(fetchData)
</script>

<style scoped>
.guard-point-content {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 24px;
}
.el-card {
  background: #fff;
  border-radius: 8px;
}
.search-bar {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.map-search-bar {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
}
</style>
